<?php

/**
 * author actions.
 *
 * @package    embeddForm2
 * @subpackage author
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class authorActions extends sfActions {

    public function executeIndex(sfWebRequest $request) {
        $this->authors = Doctrine::getTable('Author')
                        ->createQuery('a')
                        ->execute();
    }

    public function executeNew(sfWebRequest $request) {
        $this->form = new AuthorForm();
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new AuthorForm();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($author = Doctrine::getTable('Author')->find(array($request->getParameter('id'))), sprintf('Object author does not exist (%s).', $request->getParameter('id')));
        $this->form = new AuthorForm($author);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
        $this->forward404Unless($author = Doctrine::getTable('Author')->find($request->getParameter('id')), sprintf('Object author does not exist (%s).', $request->getParameter('id')));
        $data = $request->getParameter('author');

        //get the submit value from the request, and split it into an array of command, id
        $submit = ($request->hasParameter('submit') ? $request->getParameter('submit') : '_');
        $submit = explode('_', $submit);

        switch ($submit[0]) {
            case 'insert':
                $author['Books'][] = new Book();
                break;
            case 'delete':
                $this->forward404Unless($book = Doctrine::getTable('Book')->find($submit[1]));
                unset($data['book_' . $book['id']]);
                $book->delete();
                break;
        }
        $this->form = new AuthorForm($author);

        $this->processForm($data, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($author = Doctrine::getTable('Author')->find(array($request->getParameter('id'))), sprintf('Object author does not exist (%s).', $request->getParameter('id')));
        $author->delete();

        $this->redirect('author/index');
    }

    protected function processForm($data, sfForm $form) {
        $form->bind($data);
        if ($form->isValid()) {
            $author = $form->save();

            $this->redirect('author/edit?id=' . $author['id']);
        }
    }

}
